package com.example.apollotogit.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;

import javax.annotation.PostConstruct;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

public class GetJsonUtil {

    HashMap<String, String> map = new HashMap();
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @PostConstruct
    public HashMap<String, String> GetAreaCode(String jsonAddress) {
        try {
            ClassPathResource classPathResource = new ClassPathResource(jsonAddress);
            String str = IOUtils.toString(new InputStreamReader(classPathResource.getInputStream(), "UTF-8"));
            map = JSONObject.parseObject(str, HashMap.class);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return map;
    }

    /**
     * 读取json文件并且转换成字符串
     *
     * @return
     * @throws IOException
     */
    public static String readJsonData() throws IOException {
        // 读取文件数据
        //System.out.println("读取文件数据util");
        String pactFile = "/data/svnrepo/json/apollotogit.json";
        //String pactFile = "src/main/resources/static/address.json";
        StringBuffer strbuffer = new StringBuffer();
        File myFile = new File(pactFile);
        if (!myFile.exists()) {
            System.err.println("Can't Find " + pactFile);
        }
        try {
            FileInputStream fis = new FileInputStream(pactFile);
            InputStreamReader inputStreamReader = new InputStreamReader(fis, "UTF-8");
            BufferedReader in = new BufferedReader(inputStreamReader);

            String str;
            while ((str = in.readLine()) != null) {
                strbuffer.append(str);  //new String(str,"UTF-8")
            }
            in.close();
        } catch (IOException e) {
            e.getStackTrace();
        }
        //System.out.println("读取文件结束util");
        return strbuffer.toString();
    }

    public static Map getAddress() throws IOException {
        String s = readJsonData();
        System.out.println("read local json completed");
        JSONObject jobj = JSON.parseObject(s);
        String s1 = JSON.toJSONString(jobj);
        Map map1 = JSON.parseObject(s1, Map.class);
        return map1;
    }
}